<script setup>
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import { studentService } from '../../services/student'
import SearchBar from '../../components/studentlist/SearchBar.vue'
import DataTable from '../../components/common/DataTable.vue'
import { showSuccess, showWarning, showError } from '../../utils/message'
import AssignDialog from '../../components/studentlist/AssignDialog.vue'
import { useStudentStore } from '../../stores/student'
import AddStudentDialog from '../../components/studentlist/AddStudentDialog.vue'
import ActivateDialog from '../../components/studentlist/ActivateDialog.vue'
import UpdatePointsDialog from '../../components/studentlist/UpdatePointsDialog.vue'
import { ElMessageBox } from 'element-plus'

// 表格数据
const tableData = ref([])
// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格列配置
const columns = [
  { prop: 'account', label: '账号', width: '120', align: 'center' },
  { prop: 'name', label: '姓名', width: '100', align: 'center' },
  { prop: 'phone', label: '手机号', width: '120', align: 'center' },
  { prop: 'school', label: '学校', align: 'center' },
  { prop: 'class', label: '班级', width: '120', align: 'center' },  // 使用格式化后的class属性
  { prop: 'group', label: '小组', width: '80', align: 'center' },   // 使用格式化后的group属性
  { prop: 'teacher', label: '老师', width: '100', align: 'center' },
  { prop: 'points', label: '积分', width: '80', align: 'center' },
  { 
    prop: 'expireTime', 
    label: '到期时间', 
    width: '160', 
    align: 'center',
    sortable: true 
  },
  {
    slot: 'actions',
    label: '操作',
    align: 'center',
    fixed: 'right'
  }
]

const loading = ref(false)

// 添加对话框引用
const assignDialogRef = ref(null)
const addDialogRef = ref(null)
const activateDialogRef = ref(null)
const updatePointsDialogRef = ref(null)

// 加载学生数据
const loadStudents = async (searchParams = {}) => {
  try {
    loading.value = true
    const { data, total } = await studentService.getStudents({
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      filters: searchParams
    })
    tableData.value = data
    pagination.value.total = total
  } catch (error) {
    showError('加载学生数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 监听数据加载完成后恢复选中状态
watch(() => loading.value, async (newVal) => {
  if (!newVal && studentStore.selectedStudents.length > 0) {
    await nextTick()
    const storedSelection = studentStore.selectedStudents
    // 确保表格组件已经更新
    setTimeout(() => {
      dataTableRef.value?.setSelection(storedSelection)
    }, 0)
  }
})

// 处理搜索
const handleSearch = async (params) => {
  pagination.value.currentPage = 1
  await loadStudents(params)
}

// 处理表格操作
const handleTableAction = async ({ action, row }) => {
  try {
    switch (action) {
      case 'edit':
        studentStore.setCurrentStudent(row)
        addDialogRef.value?.openDialog()
        break
      case 'delete':
        try {
          await ElMessageBox.confirm(
            `确定要删除学生 ${row.name}(${row.account}) 的账号信息吗？`,
            '删除确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
          await studentService.deleteStudents([row.id])
          showSuccess('删除成功')
          await loadStudents()
        } catch (err) {
          if (err !== 'cancel') {
            throw err
          }
        }
        break
      case 'activate':
        studentStore.setSelectedStudents([row])
        activateDialogRef.value?.openDialog()
        break
      case 'assign':
        studentStore.setSelectedStudents([row])
        assignDialogRef.value?.openAssignDialog()
        break
      case 'points':
        studentStore.setCurrentStudent(row)
        updatePointsDialogRef.value?.openDialog()
        break
      case 'reset':
        console.log('重置', row)
        break
    }
  } catch (error) {
    showError('操作失败')
    console.error(error)
  }
}

// 选中的行数据
const dataTableRef = ref(null)
const selection = ref([])

const studentStore = useStudentStore()

// 修改为使用一个独立的状态来存储当前选中的学生
const selectedStudents = ref([])

// 修改选择处理逻辑
const handleSelectionChange = (selected) => {
  // 同时更新本地状态和 store 状态
  nextTick(() => {
    selectedStudents.value = [...selected]
    studentStore.setSelectedStudents(selected)
  })
}

// 修改批量操作方法
const handleBatchAction = async (action) => {
  if (action === 'add') {  // 添加这个判断
    addDialogRef.value?.openDialog()
    return
  }
  if (action === 'batchAdd') {
    addDialogRef.value?.openDialog()
    return
  }
  if (action !== 'export' && !selectedStudents.value.length) {
    showWarning('请选择要操作的学生')
    return
  }
  
  try {
    switch (action) {
      case 'assign':
        assignDialogRef.value?.openAssignDialog()
        break
      case 'delete':
        await studentService.deleteStudents(selectedStudents.value.map(item => item.id))
        showSuccess('批量删除成功')
        selectedStudents.value = []
        break
      case 'activate':
        activateDialogRef.value?.openDialog()
        break
      // ...其他批量操作处理
      case 'import':
        console.log('批量导入')
        break
      case 'batchAdd':
        console.log('批量添加')
        break
      case 'export':
        await studentService.exportStudents()
        break
    }
    await loadStudents()
  } catch (error) {
    showError('操作失败')
    console.error(error)
  }
}

// 处理分配确认
const handleAssignConfirm = async (formData) => {
  try {
    // 使用 store 中的选中数据
    const selectedIds = studentStore.selectedStudents.map(item => item.id)
    await studentService.batchAssign(selectedIds, formData)
    showSuccess('分配成功')
    // 清空选择状态
    selectedStudents.value = []
    studentStore.clearSelection()
    await loadStudents()
  } catch (error) {
    showError('分配失败')
    console.error(error)
  }
}

// 处理编辑或新增学生
const handleAddStudent = async (formData) => {
  try {
    if (formData.id) {
      // 编辑模式
      await studentService.updateStudent(formData.id, formData)
      showSuccess('更新成功')
    } else {
      // 新增模式
      await studentService.addStudent(formData)
      showSuccess('添加成功')
    }
    await loadStudents()
  } catch (error) {
    if (error.message === '该账号已被使用') {
      showError('添加失败：该账号已被使用')
    } else {
      showError(formData.id ? '更新失败' : '添加失败')
    }
    console.error(error)
  }
}

// 处理激活确认
const handleActivateConfirm = async (formData) => {
  try {
    await studentService.activateStudents(
      studentStore.selectedStudents.map(item => item.id),
      formData.activeDays
    )
    showSuccess('激活成功')
    studentStore.clearSelection()
    await loadStudents()
  } catch (error) {
    showError('激活失败')
    console.error(error)
  }
}

// 处理积分修改
const handleUpdatePoints = async (formData) => {
  try {
    const student = studentStore.currentStudent
    if (!student) return
    
    await studentService.updatePoints([student.id], formData.points)
    showSuccess('积分修改成功')
    studentStore.clearCurrentStudent()
    await loadStudents()
  } catch (error) {
    showError('修改积分失败')
    console.error(error)
  }
}

// 监听分配对话框关闭
const handleAssignCancel = () => {
  const selection = studentStore.cancelSelection()
  dataTableRef.value?.setSelection(selection)
}

// 添加对话框关闭时清理当前编辑的学生
const handleDialogClose = () => {
  studentStore.clearCurrentStudent()
}

// 监听分页变化
watch(
  () => [pagination.value.currentPage, pagination.value.pageSize],
  () => loadStudents()
)

onMounted(() => {
  loadStudents()
})
</script>

<template>
  <div class="student-list">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <div class="batch-actions-left" v-if="selectedStudents.length">
            <el-button type="primary" @click="handleBatchAction('assign')">
              统一分配
            </el-button>
            <el-button type="danger" @click="handleBatchAction('delete')">
              批量删除
            </el-button>
          </div>
          <span v-else>学生列表</span>
          
          <div class="header-actions">
            <el-dropdown split-button type="primary" @click="handleBatchAction('add')" @command="handleBatchAction">
              添加学生
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="batchAdd">批量添加</el-dropdown-item>
                  <el-dropdown-item command="import">批量导入</el-dropdown-item>
                  <el-dropdown-item command="activate">批量激活</el-dropdown-item>
                  <el-dropdown-item command="export" divided>导出数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
      
      <search-bar @search="handleSearch" />
      
      <data-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        :columns="columns"
        v-model:pagination="pagination"
        @action="handleTableAction"
        @selection-change="handleSelectionChange"
      >
        <template #actions="{ row }">
          <el-button link type="primary" @click="handleTableAction({ action: 'edit', row })">
            编辑
          </el-button>
          <el-button link type="primary" @click="handleTableAction({ action: 'assign', row })">
            分配
          </el-button>
          <el-button link type="primary" @click="handleTableAction({ action: 'activate', row })">
            激活
          </el-button>
          <el-button link type="primary" @click="handleTableAction({ action: 'points', row })">
            修改积分
          </el-button>
          <!-- <el-button link type="primary" @click="handleTableAction({ action: 'reset', row })">
            重置
          </el-button> -->
          <el-button link type="danger" @click="handleTableAction({ action: 'delete', row })">
            删除
          </el-button>
        </template>
      </data-table>
    </el-card>
    <assign-dialog
      ref="assignDialogRef"
      :selected-students="selectedStudents"
      @confirm="handleAssignConfirm"
      @cancel="handleAssignCancel"
    />
    <add-student-dialog
      ref="addDialogRef"
      :edit-mode="Boolean(studentStore.currentStudent)"
      :edit-data="studentStore.currentStudent"
      @confirm="handleAddStudent"
      @closed="handleDialogClose"
    />
    <activate-dialog
      ref="activateDialogRef"
      @confirm="handleActivateConfirm"
    />
    <update-points-dialog
      ref="updatePointsDialogRef"
      @confirm="handleUpdatePoints"
    />
  </div>
</template>

<style scoped>
.student-list {
  height: 100%;
}

.page-card {
  margin: 0px;
  background-color: var(--el-bg-color);
  border-color: var(--el-border-color-lighter);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-actions-left {
  display: flex;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dropdown-menu) {
  background-color: var(--el-bg-color);
  border-color: var(--el-border-color-lighter);
}

:deep(.el-dropdown-menu__item:not(.is-disabled):hover) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-card__header) {
  border-bottom-color: var(--el-border-color-lighter);
}
</style>
